package core;

import gui.StatusPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.Timer;

import command.CommandBroadcaster;
import command.CommandGenerator;

public class TurnTimer extends Observable implements ActionListener{
	private static TurnTimer me;
	
	private Timer timer;
	private int timeLeft;
	
	public static TurnTimer getInstance(){
		if(me == null)
			me = new TurnTimer();
		return me;
	}
	
	private TurnTimer(){
		init();
	}
	
	private void init(){
		addObserver(StatusPanel.getInstance());
		startTimer();
	}
	
	private void startTimer(){
		timeLeft = Constants.TURNTIME;
		timer = new Timer(1000, (ActionListener) this);
		timer.start();
	}
	
	public void resetTimer(){
		timeLeft = Constants.TURNTIME;
	}
	
	private void broadcast(int tl){
		setChanged();
		notifyObservers(tl);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		timeLeft--;
		if(timeLeft==0){
			resetTimer();
			CommandBroadcaster.sendCommand(CommandGenerator.getInstance().generateEndTurnCommand());
		}
		broadcast((Integer)timeLeft);
	}
}
